package com.soo.hoo.admin.component;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * <p>默认的websocket拦截器，处理握手阶段的一些校验</p>
 *
 * @author 杨燚
 * @since 2023/6/8
 */
@Slf4j
@Component
public class DefaultWebSocketInterceptor implements HandshakeInterceptor {

    /**
     * 收信人id即用户id的字段名
     */
    private static final String RECEIVER_ID_KEY = "receiverId";

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        log.info("Websocket开始握手");
        if (!StpUtil.isLogin()) {
            log.warn("Websocket握手失败：尚未登录，请先登录");
            return false;
        }
        attributes.put(RECEIVER_ID_KEY, StpUtil.getLoginIdAsString());
        return true;
    }

    @Override
    public void afterHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response, @NotNull WebSocketHandler wsHandler, Exception exception) {
        log.info("Websocket握手成功");
    }
}
